package com.thatvn.diemtinvietnam;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.util.Log;
import android.util.JsonReader;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.thatvn.diemtinvietnam.MainActivity;

public class jsonParseTrend {
	  
	   //topic
	   private String title = "title";
	   private String keyword = "keyword";
	   private String imageMain = "image";
	   //child
	   private String id = "id";
	   private String name = "name";
	   private String image = "image";
	   private String link = "link";
	   private String source = "maindomain";	  
	   private String hasContent = "hasContent";
	  
	   private String urlString = null;
	   
	   
	   public volatile boolean parsingComplete = true;
	   public ArrayList<HashMap<String, String>> itemNewsList;
	   public ArrayList<Object> itemNewsListChild;
	   //public ArrayList<HashMap<Object, Object>> itemNewsListChildDetail;
	   
	   public jsonParseTrend(String url){
	      this.urlString = url;
	   }
	   public String getTitle(){
	      return title;
	   }
	   public String getImage(){
	      return image;
	   }
	   public ArrayList<HashMap<String, String>> getItemNewsList(){
		   return itemNewsList;
	   }
	   public ArrayList<Object> getItemNewsListChild(){
		   return itemNewsListChild;
	   }
	   
	   @SuppressLint("NewApi")
	   public void readAndParseJSON(String in) {
		  JSONArray items = null; 
		  //String preTitle="";
	      try {
	    	  JSONObject jsonObj = new JSONObject(in);
        
        // Getting JSON Array node
	    	  items = jsonObj.getJSONArray("news");	    	  
	    	  //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", String.valueOf(items.length()));
	    	  itemNewsList = new ArrayList<HashMap<String, String>>();
	    	  itemNewsListChild = new ArrayList<Object>();
	    	
	    	  String preKeyword="";
	    	  //Init
	    	  ArrayList<HashMap<String, String>> arrChild=new  ArrayList<HashMap<String, String>>();
	    	  HashMap<String, String> itemDetailChild = new HashMap<String, String>();
	    	 
	    	  for (int i = 0; i < items.length(); i++) {
            
            try{
          	  JSONObject c = items.getJSONObject(i);
                //if (c.isNull("id")) continue;
                //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok3");
                //DOC TIN CHINH THUC
	                  //id=  c.getString(MainActivity.KEY_ID); 
	                  if (!c.isNull("title")){
	                	  title = c.getString("title");
	                  }else {title="";}
	                  keyword = c.getString("keyword");
	                  
	                  if (!c.isNull("image")){
	                	  imageMain = c.getString("image");
	                  }else {imageMain="";}
	                 
	                  
	                  
	                  
	                  HashMap<String, String> itemDetail = new HashMap<String, String>();
	                  
	                  //Them cho tin chinh
	                  if (keyword!=null && !keyword.isEmpty() && !keyword.equals(preKeyword)){
	                	  if (arrChild.size()>0) itemNewsListChild.add(arrChild);	                	  
		                  itemDetail.put("keyword", keyword);
		                  itemDetail.put("title", title);
		                  itemDetail.put("image", imageMain);
		                  itemNewsList.add(itemDetail);
		                  itemDetailChild = new HashMap<String, String>();
		                  arrChild=new  ArrayList<HashMap<String, String>>();
		                	//Init new first child
			                  if (!c.isNull("name")){
			                	  //child
				                  if (!c.isNull("image")){
				                	  image = c.getString(MainActivity.KEY_IMAGE);
				                  }else {image="";}
				                  name=c.getString("name");
				                  link=c.getString(MainActivity.KEY_LINK); 
				                  source=c.getString(MainActivity.KEY_SOURCE);
				                  id=c.getString(MainActivity.KEY_ID);
				                  hasContent=c.getString(MainActivity.KEY_HASCONTENT);
				                  
	    		                  itemDetailChild.put("name", name);
	    		                  itemDetailChild.put("link", link);
	    		                  itemDetailChild.put("image", image);
	    		                  itemDetailChild.put("maindomain", source);	
	    		                  itemDetailChild.put("id", id);
	    		                  itemDetailChild.put("hasContent", hasContent);
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    	                  }else {
//	    		                
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    		                  //itemNewsListChildDetail.;	    		                 
	    	                  }
			                 
	                  }else{
	                	  if(keyword.equals(preKeyword)){
	                		  if (!c.isNull("name")){
	                			  if (!c.isNull("image")){
				                	  image = c.getString(MainActivity.KEY_IMAGE);
				                  }else {image="";}
				                  name=c.getString("name");
				                  link=c.getString(MainActivity.KEY_LINK); 
				                  source=c.getString(MainActivity.KEY_SOURCE);
				                  id=c.getString(MainActivity.KEY_ID);
				                  hasContent=c.getString(MainActivity.KEY_HASCONTENT);
				                  
	    		                  itemDetailChild.put("name", name);
	    		                  itemDetailChild.put("link", link);
	    		                  itemDetailChild.put("image", image);
	    		                  itemDetailChild.put("maindomain", source);
	    		                  itemDetailChild.put("id", id);
	    		                  itemDetailChild.put("hasContent", hasContent);
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    	                  }else {
//	    		                
	    		                  arrChild.add(itemDetailChild);
	    		                  itemDetailChild = new HashMap<String, String>();
	    		                  //itemNewsListChildDetail.;	    		                 
	    	                  }
	                		  
	                	  }
	                  }
	                  //Log.e("aaaa", "22222222");
	                  preKeyword=keyword;
	                  
	                  //Log.e("items.lengthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "ok4");
	                  //DOC TIN LIEN QUAN
	                  
	                  
	                 
	                  
	                  //Log.e("aaaa", "111111");
	                 
	                 
	                  //Log.e("itemDetail.put", "itemDetail.put");
	                  // adding contact to contact list
	                  
	                  
	                  //Log.e("aaaa", "BBBBBBBBBBBBBBBBBBBBBBBB");
            }catch(Exception ex)
            {
          	  //Log.e("ExceptionExceptionExceptionExceptionExceptionException", ex.toString());
            }
        }//FOR
	         parsingComplete = false;
	         arrChild.add(itemDetailChild);
	         if (arrChild.size()>0) itemNewsListChild.add(arrChild);

	        } catch (Exception e) {
	           // TODO Auto-generated catch block
	        	//Log.e("ExceptionExceptionExceptionExceptionExceptionException", e.toString());
	           e.printStackTrace();
	        }

	   }
	   public String fetchJSON() throws IOException{
	      
	         try {
	            URL url = new URL(urlString);
	            //Log.e("fetchJSON", urlString);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setReadTimeout(10000 /* milliseconds */);
	            conn.setConnectTimeout(15000 /* milliseconds */);
	            conn.setRequestMethod("GET");
	            conn.setDoInput(true);
	            //conn.setRequestProperty(field, newValue)
	            // Starts the query
	            conn.connect();
	            //Log.e("fetchJSON", "ok1");
		         //InputStream stream = conn.getInputStream();
	            InputStreamReader reader = null;
		         StringBuilder builder = new StringBuilder();
	
		         try {
		             // ...
		             reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
		             char[] buffer = new char[8192];
	
		             for (int length = 0; (length = reader.read(buffer)) > 0;) {
		                 builder.append(buffer, 0, length);
		                 
		             }
		         } finally {
		             if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
		         }
	
		         String html = builder.toString();
		         
		         String data = html;//convertStreamToString(stream);
	      		 data="{\"news\":"+data+"}";
	      		 //Log.e("fetchJSON", data);
	      		 readAndParseJSON(data);
	      		 //stream.close();
	      		 return data;
	         } catch (Exception e) {
	            e.printStackTrace();
	            return "0";
	         }	         
	      		
	   }
	   static String convertStreamToString(java.io.InputStream is) {
	      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	      return s.hasNext() ? s.next() : "";
	   }
}
